package xipujewel.xipujewel.web.account;

import java.io.IOException;
import java.util.List;
import java.util.Map;

import javax.servlet.ServletRequest;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import net.esoar.modules.utils.WebUtil;
import net.esoar.modules.web.BaseController;
import net.esoar.modules.web.pojo.JPage;
import net.esoar.modules.web.pojo.WebPojo;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import xipujewel.xipujewel.entity.account.User;
import xipujewel.xipujewel.entity.app.ExchangeRate;
import xipujewel.xipujewel.entity.app.Jewel;
import xipujewel.xipujewel.entity.app.Order;
import xipujewel.xipujewel.entity.app.Ring;
import xipujewel.xipujewel.service.ExchangeRateManager;
import xipujewel.xipujewel.service.OrderManager;
import xipujewel.xipujewel.service.account.UserManager;
import xipujewel.xipujewel.utils.UserUtil;

/**
 * 
 * @author hang
 *
 */
@Controller
@RequestMapping(value = "/order")
public class OrderController extends BaseController<Order> {

	@Autowired
	private OrderManager orderManager;

	@Autowired
	private UserManager userManager;

	@Autowired
	private ExchangeRateManager exchangeRateManager;

	@RequestMapping("")
	public String list(Model model, ServletRequest request) {
		Map<String, Object> searchParams = getFilters(request);
		initOrder("submitTime", JPage.DESC);
		User cUser = userManager.findByLoginNameAndType01(UserUtil.getCurrentUserLoginName());
		if (cUser.getType() == 1) {
			searchParams.put("EQ_user.parent.id", cUser.getId());
		}

		jPage = orderManager.search(searchParams, jPage);
		model.addAttribute("cUser", cUser);
		return "order/order-list";
	}

	@RequestMapping("detail/{id}/{type}")
	public String detail(@PathVariable("id") Long id, @PathVariable("type") Long type, Model model) {
		Order order = orderManager.get(id);
		List<Jewel> jewels = order.getJewels();
		List<Ring> rings = order.getRings();
		User cUser = order.getUser().getParent();
		model.addAttribute("cUser", cUser);
		model.addAttribute("user", order.getUser());
		model.addAttribute("order", order);
		if (type == 1) {
			initOrderJewel(jewels, cUser);
			model.addAttribute("jewels", jewels);
			return "order/order-jewel-detail";
		} else {
			if (cUser.getType() == 1) {
				initOrderRing(rings, cUser);
			}
			model.addAttribute("rings", rings);
			return "order/order-ring-detail";
		}
	}

	@RequestMapping(value = "downloadOrder/{id}", method = RequestMethod.GET)
	public void downloadOrder(@PathVariable("id") Long id, HttpServletRequest httpRequest, HttpServletResponse response)
			throws IOException {
		Order order = orderManager.get(id);
		List<Jewel> jewels = order.getJewels();
		List<Ring> rings = order.getRings();
		User cUser = order.getUser().getParent();
		initOrderJewel(jewels, cUser);
		initOrderRing(rings, cUser);

		/*	HttpHeaders headers = new HttpHeaders();
			headers.setContentType(MediaType.APPLICATION_OCTET_STREAM);
			headers.setContentDispositionFormData("attachment", new Date().getTime() + ".xls");// 设置下载文件名
			return new ResponseEntity<byte[]>(orderManager.getEXL(jewels, rings, cUser).getBytes(), headers, HttpStatus.OK);*/
		String fileName = new String(order.getOrderNum().getBytes(), "ISO8859_1");
		response.setHeader("Content-disposition", "attachment; filename=" + fileName + ".xlsx");
		// 确保发送的当前文本格式
		response.setContentType("application/vnd.ms-excel");
		orderManager.getEXL(jewels, rings, cUser).write(response.getOutputStream());
		response.getOutputStream().flush();
		response.getOutputStream().close();
	}

	@RequestMapping(value = DELETE, produces = MediaType.APPLICATION_JSON_VALUE)
	@ResponseBody
	public WebPojo delete(@PathVariable(ID) Long id) {
		orderManager.deleteOrder(id);
		return WebUtil.getNavTabAjaxDone("w_order");
	}

	@RequestMapping(value = DELETES, produces = MediaType.APPLICATION_JSON_VALUE)
	@ResponseBody
	public WebPojo deleteByIds(@RequestParam(IDS) List<Long> ids) {
		orderManager.deleteOrders(ids);
		return WebUtil.getNavTabAjaxDone("w_order");
	}

	@RequestMapping(value = "deal/{id}", produces = MediaType.APPLICATION_JSON_VALUE)
	@ResponseBody
	public WebPojo deal(@PathVariable(ID) Long id) {
		Order order = orderManager.get(id);
		order.setStatus(1);
		orderManager.save(order);
		return WebUtil.getNavTabAjaxDone("w_order");
	}

	@Override
	public String baseMapping() {
		// TODO Auto-generated method stub
		return null;
	}

	@Override
	public String getModelName() {
		// TODO Auto-generated method stub
		return null;
	}

	private void initOrderRing(List<Ring> rings, User cUser) {
		for (Ring ring : rings) {
			float secondPrice = ring.getPrice() * cUser.getPriceBaseNumber().getRingBaseNumber();
			ring.setSecondPrice(secondPrice);
		}
	}

	private void initOrderJewel(List<Jewel> jewels, User cUser) {
		ExchangeRate exchangeRate = exchangeRateManager.getAll().get(0);
		for (Jewel jewel : jewels) {//重量X国际报价X折扣X汇率
			float discount2 = (float) ((100.0 + jewel.getDiscount() + cUser.getPriceBaseNumber().getJewelBaseNumBer()) / 100.0);
			float discount = (float) ((100.0 + jewel.getDiscount()) / 100.0);
			float secondPrice = jewel.getWeight() * jewel.getInternationalPrice() * (discount2)
					* exchangeRate.getRate();
			int rmbPrice = (int) (jewel.getWeight() * jewel.getInternationalPrice() * (discount) * exchangeRate
					.getRate());
			jewel.setSecondPrice(secondPrice);
			if (discount2 > 1) {
				jewel.setDiscount2(String.valueOf((discount2 - 1) * 100));
			} else {
				jewel.setDiscount2("-" + String.valueOf((1 - discount2) * 100));
			}
			jewel.setPriceRMB(rmbPrice);
		}
	}

	@ModelAttribute("order")
	public Order getModel(@RequestParam(value = ID, required = false) Long id) {
		if (id != null) {
			return orderManager.get(id);
		}
		return null;
	}

}
